package com.ihr360.payroll.controller.salarytask;

import com.google.common.collect.Lists;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.model.type.FieldSource;
import com.ihr360.commons.vo.ResultInfo;
import com.ihr360.excel.vo.ImportHeaderGroup;
import com.ihr360.excel.vo.ImportHeaderItem;
import com.ihr360.excel.vo.ImportHeaderResult;
import com.ihr360.excel.vo.ImportRequest;
import com.ihr360.maven.plugin.ModuleCodeStore;
import com.ihr360.maven.plugin.annotation.FunctionDefinition;
import com.ihr360.maven.plugin.annotation.ModuleDefinition;
import com.ihr360.payroll.model.vo.SalaryFieldVo;
import com.ihr360.payroll.service.salaryplan.SalaryPlanService;
import com.ihr360.payroll.service.salarytask.SalaryTaskService;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Stone.Shi
 * @description
 * @date 2018-05-21 17:14:11.
 */
@Api(value = "薪资数据导入相关接口")
@RestController
@RequestMapping("/salary/tasks")
@ModuleDefinition(mainModuleCode = ModuleCodeStore.Module.SALARY_CODE,
        mainModuleName = ModuleCodeStore.Module.SALARY_NAME,
        subModuleCode = ModuleCodeStore.Module.Salary.SALARY_TASK_CODE,
        subModuleName = ModuleCodeStore.Module.Salary.SALARY_TASK_NAME)
public class SalaryTaskImportController {
    @Autowired
    private SalaryTaskService salaryTaskService;

    @Autowired
    private SalaryPlanService salaryPlanService;

    ///////////////////////////下载模板、导入////////////////////////////////////////////

    @FunctionDefinition(functionName = "获取全部薪资字段", functionCode = ModuleCodeStore.Function.VIEW)
    @ApiOperation(value = "获取薪资方案的全部薪资字段数据")
    @GetMapping(value = "/getSalaryFields/{id}")
    public ImportHeaderResult getTemplateSelectableFields(@PathVariable(name = "id") Long planId) {
        ImportHeaderResult result = new ImportHeaderResult();

        List<SalaryFieldVo> planSalaryFields = salaryPlanService.getPlanSalaryFields(planId);
        if (CollectionUtils.isEmpty(planSalaryFields)) {
            result.setGroups(Collections.emptyList());
            return result;
        }

        Map<Boolean, List<SalaryFieldVo>> listMap = planSalaryFields.stream()
                .collect(Collectors.groupingBy(field -> field.getSource() == FieldSource.INPUT));

        ArrayList<ImportHeaderGroup> groups = Lists.newArrayList();

        ImportHeaderGroup inputGroup = new ImportHeaderGroup("INPUT", "输入项");
        groups.add(inputGroup);
        List<SalaryFieldVo> selectedVos = listMap.get(Boolean.TRUE);
        if (CollectionUtils.isNotEmpty(selectedVos)) {
            ArrayList<ImportHeaderItem> inputItems = Lists.newArrayList();
            selectedVos.forEach(vo -> inputItems.add(new ImportHeaderItem(vo.getCode(), vo.getName(), true)));
            inputGroup.setHeaderItems(inputItems);
        }

        ImportHeaderGroup notinputGroup = new ImportHeaderGroup("NOT_INPUT", "非输入项");
        groups.add(notinputGroup);
        List<SalaryFieldVo> unselectedVos = listMap.get(Boolean.FALSE);
        if (CollectionUtils.isNotEmpty(unselectedVos)) {
            ArrayList<ImportHeaderItem> notinputItems = Lists.newArrayList();
            unselectedVos.forEach(vo -> notinputItems.add(new ImportHeaderItem(vo.getCode(), vo.getName(), false)));
            notinputGroup.setHeaderItems(notinputItems);
        }

        result.setGroups(groups);
        return result;
    }

    @FunctionDefinition(functionName = "按照选定的薪资字段下载excel模板", functionCode = ModuleCodeStore.Function.VIEW)
    @ApiOperation(value = "按照选定的薪资字段下载excel模板")
    @GetMapping(value = "/periods/template/{id}")
    public void downloadTemplateBySelectedFields(@PathVariable(name = "id") Long payPeriodId,
                                                 @RequestParam List<String> fieldList,
                                                 @RequestParam boolean containsData,
                                                 HttpServletResponse response) throws IOException {
        response.setHeader("x-filename", URLEncoder.encode("薪资导入模板.xls", "UTF-8"));
        salaryTaskService.downloadTemplateBySelectedFields(payPeriodId, fieldList, containsData, response.getOutputStream());
    }

    @FunctionDefinition(functionName = "导入薪资数据", functionCode = ModuleCodeStore.Function.VIEW)
    @ApiOperation(value = "导入薪资数据")
    @PostMapping(value = "/periods/import/{id}")
    @DisableResponseAdvice
    public ResultInfo importExcel(@PathVariable(name = "id") Long payPeriodId,
                                  @RequestBody ImportRequest importRequest) {
        salaryTaskService.importExcel(payPeriodId, importRequest);
        return new ResultInfo.Builder<>().success();
    }

    @FunctionDefinition(functionName = "导入薪资数据", functionCode = ModuleCodeStore.Function.VIEW)
    @ApiOperation(value = "导出薪资数据")
    @GetMapping(value = "/periods/export/{id}")
    public void export(@PathVariable(name = "id") Long payPeriodId,
                       HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        String fileName = new String("salary.xls".getBytes("UTF-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        salaryTaskService.exportExcel(payPeriodId, response.getOutputStream());
    }
}
